package com.merlin.demo_wellshape.service;

import com.merlin.demo_wellshape.pojo.CheckInRecord;
import com.merlin.demo_wellshape.pojo.ResponseMessage;
import com.merlin.demo_wellshape.pojo.User;
import com.merlin.demo_wellshape.repository.CheckInRecordRepository;
import com.merlin.demo_wellshape.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.Base64;
import java.util.List;

@Service // 将UserService注入到spring容器中
public class UserService implements UserServiceImpl {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private CheckInRecordRepository checkInRecordRepository;


    @Override
    public ResponseMessage saveUser(User user) {
        if (isUserPhoneExists(user.getUserPhone())) {
            return new ResponseMessage(409, "手机号码已被注册，请使用其他手机号码。", null);
        }
        // 如果 avatar 字段为空，则设置为默认值
        if (user.getAvatar() == null || user.getAvatar().isEmpty()) {
            user.setAvatar(User.DEFAULT_AVATAR_PATH);
        }
        userRepository.save(user);  // 保存用户到数据库
        return new ResponseMessage(200, "用户添加成功", user);
    }

    @Override
    public boolean isUserPhoneExists(String userPhone) {
        return userRepository.existsByUserPhone(userPhone);
    }

    @Override
    public User getUserByUserId(int id) {
        if (userRepository.findById(id).isEmpty()) {
            throw new IllegalArgumentException("用户不存在，参数异常");
        }
        return userRepository.findById(id).orElse(null);
        // return userRepository.findById(id).get();
    }

    @Override
    public User getUserByPhone(String userPhone) {
        return userRepository.findByUserPhone(userPhone);
    }

    @Override
    public User updateUser(int userId, User userDetails) {
        return userRepository.save(userDetails);
    }

    // @Override
    // public User updateUser(int userId, User userDetails) {
    //     User existingUser = userRepository.findById(userId).orElse(null);
    //     if (existingUser != null) {
    //         existingUser.setUsername(userDetails.getUsername());
    //         existingUser.setPassword(userDetails.getPassword());
    //         existingUser.setUserPhone(userDetails.getUserPhone());
    //         existingUser.setBirthDate(userDetails.getBirthDate());
    //         existingUser.setSignature(userDetails.getSignature());
    //         existingUser.setAvatar(userDetails.getAvatar());
    //         return userRepository.save(existingUser);
    //     }
    //     return null;
    // }

    @Override
    public String getAvatarBase64(int userId) {
        User user = getUserByUserId(userId);
        if (user == null || user.getAvatar() == null) {
            System.out.println("用户不存在或未设置头像");
            return null;
        }

        try {
            // 构建文件路径
            String baseDir = "src/main/resources/static/avatar";
            Path avatarFilePath = Paths.get(baseDir, user.getAvatar());

            // 读取文件并转换为Base64编码
            byte[] avatarBytes = Files.readAllBytes(avatarFilePath);
            return Base64.getEncoder().encodeToString(avatarBytes);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean deleteUser(int userId) {
        try {
            userRepository.deleteById(userId);
            return true; // 删除成功
        } catch (Exception e) {
            // 记录日志
            e.printStackTrace();
            return false; // 删除失败
        }
    }

    @Override
    public void saveCheckInRecord(CheckInRecord checkInRecord) {
        checkInRecordRepository.save(checkInRecord);
    }

    @Override
    public List<CheckInRecord> getCheckInRecordsByUserAndDateRange(User user, LocalDate startDate, LocalDate endDate) {
        return checkInRecordRepository.findByUserAndCheckInDateBetween(user, startDate, endDate);
    }

    @Override
    public boolean hasCheckedInToday(User user, LocalDate date) {
        return checkInRecordRepository.existsByUserAndCheckInDate(user, date);
    }

    // 根据用户ID和手机号获取打卡记录
    @Override
    public List<CheckInRecord> getCheckInRecordsByUserIdAndUserPhone(int userId, String userPhone) {
        return checkInRecordRepository.findByUserIdAndUserPhone(userId, userPhone);
    }

    // 新增方法：插入签到记录
    @Override
    public void insertCheckInRecords(String userPhone, LocalDate... dates) {
        User user = getUserByPhone(userPhone);
        if (user == null) {
            throw new RuntimeException("User not found");
        }

        for (LocalDate date : dates) {
            CheckInRecord checkInRecord = new CheckInRecord();
            checkInRecord.setUser(user);
            checkInRecord.setCheckInDate(date);
            saveCheckInRecord(checkInRecord);
        }
    }

    // 新增方法：删除签到记录
    @Override
    public boolean deleteCheckInRecord(User user, LocalDate checkInDate) {
        CheckInRecord checkInRecord = checkInRecordRepository.findByUserAndCheckInDate(user, checkInDate);
        if (checkInRecord != null) {
            checkInRecordRepository.delete(checkInRecord);
            return true;
        }
        return false;
    }
}
